package pers.jg.rrsserver.service

import org.bouncycastle.jce.provider.BouncyCastleProvider
import org.springframework.stereotype.Service
import java.nio.charset.StandardCharsets
import java.security.Security
import java.util.*
import javax.crypto.Cipher
import javax.crypto.spec.SecretKeySpec

@Service
class SafeService {

    init {
        Security.addProvider(BouncyCastleProvider())
    }

    fun createUUIDv4(): String {
        val uuid = UUID.randomUUID().toString()
        return uuid
    }
    /**
     * 3DES加密
     * @param data 待加密数据
     * @param key 密钥
     * @return 加密后的数据
     */
    fun des3Encrypt(data: String, key: String): String {
        val cipher = Cipher.getInstance("AES/ECB/PKCS7Padding")
        val keyBytes = key.toByteArray(StandardCharsets.UTF_8)
        cipher.init(Cipher.ENCRYPT_MODE, SecretKeySpec(keyBytes, "ECB"))
        val doFinal = cipher.doFinal(data.toByteArray(StandardCharsets.UTF_8))
        return String(Base64.getEncoder().encode(doFinal))
    }

    /**
     * 3DES解密
     * @param data 待解密数据
     * @param key 密钥
     * @return 解密后的数据
     */
    fun des3Decrypt(data: String, key: String): String {
        val cipher = Cipher.getInstance("AES/ECB/PKCS7Padding")
        val keyBytes = key.toByteArray(StandardCharsets.UTF_8)
        cipher.init(Cipher.DECRYPT_MODE, SecretKeySpec(keyBytes, "ECB"))
        val doFinal = cipher.doFinal(Base64.getDecoder().decode(data))
        return String(doFinal);
    }
}